import { BaseService } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { TaskAppEntity } from '../entity/app';
import { v1 as uuid } from 'uuid';
import { Provide, Scope, ScopeEnum } from '@midwayjs/core';

/**
 * 应用
 */
@Scope(ScopeEnum.Request, { allowDowngrade: true })
@Provide()
export class TaskAppService extends BaseService {
  @InjectEntityModel(TaskAppEntity)
  taskAppEntity: Repository<TaskAppEntity>;

  /**
   * 新增
   * @param param
   */
  async add(param: TaskAppEntity) {
    param.appId = uuid().replace(/-/g, '');
    param.appSecret = uuid().replace(/-/g, '');
    return await super.add(param);
  }

  /**
   * 重置密钥
   * @param id
   */
  async reset(id: number) {
    await this.taskAppEntity.update(
      { id },
      {
        appSecret: uuid().replace(/-/g, ''),
      }
    );
  }

  /**
   * 检查权限
   * @param appId
   * @param appSecret
   */
  async check(appId: string, appSecret: string) {
    const app = await this.taskAppEntity.findOneBy({ appId, status: 1 });
    if (!app || app.appSecret !== appSecret) {
      return null;
    }
    return app;
  }
}
